package mc.support.taobao.api;

import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.TaobaoResponse;

import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA. <br/>
 * User: francis    <br/>
 * Date: 13-11-12    <br/>
 * Time: 17:30  <br/>
 */
public abstract class AbstractReq<T, E> {

    protected String sessionKey;
    protected TaobaoClient taobaoClient;

    protected abstract TaobaoRequest toRequest();

    public T sessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
        return (T) this;
    }

    public T taobaoClient(TaobaoClient taobaoClient) {
        this.taobaoClient = taobaoClient;
        return (T) this;
    }

    public E send() throws ApiException {
        TaobaoResponse r = null;
        TaobaoRequest req = toRequest();
        if ( null != sessionKey ) {
            r = taobaoClient.execute( req, sessionKey );
        } else {
            r = taobaoClient.execute( req );
        }

        return ( E ) r;
    }

    protected static String connectMap(Map<String, String> map, String sep, String sep0) {
        StringBuilder s = new StringBuilder();
        int len = map.size();
        int index = 0;
        for ( Map.Entry<String, String> e : map.entrySet() ) {
            s.append( e.getKey().trim() )
                    .append( sep.trim() )
                    .append( e.getValue().trim() );
            if ( index++ != len - 1 ) {
                s.append( sep0.trim() );
            }
        }
        return s.toString();
    }


    protected static String setToString(Set<String> set) {
        StringBuilder s = new StringBuilder();

        int num = set.size();
        int i = 0;
        for ( String n : set ) {
            if ( i < num - 1 ) {
                s.append( n ).append( ',' );
            } else {
                s.append( n );
            }
            i++;
        }

        return s.toString();
    }

}
